package com.yenlien.traceyun.control.controller;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.common.bean.UserInfo;
import com.yenlien.traceyun.common.crypt.TokenUtil;
import com.yenlien.traceyun.common.exception.TokenException;
import com.yenlien.traceyun.control.bean.RestURL;
import com.yenlien.traceyun.control.interceptor.UserAuthUtil;
import com.yenlien.traceyun.control.service.rest.RestService;
import com.yenlien.traceyun.control.service.rest.UserRestService;
import com.yenlien.traceyun.webase.controller.BaseController;
import com.yenlien.traceyun.webase.utils.CheckParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-03-06
 * @description:
 **/

@RestController
@RequestMapping(value = "/user")
public class UserController extends BaseController {

    @Autowired
    private UserRestService userRestService;

    @Autowired
    private RestService restService;

    @Value("${traceyun.app.id}")
    private String appId;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 登录(小程序)
     *
     * @param userInfo
     * @return
     */
    @PostMapping(value = "/login")
    public Object login(@RequestBody JSONObject userInfo) {
        CheckParams.checkJson(userInfo, new String[]{"username", "password"});
        JSONObject userJson = userRestService.login(userInfo.getString("username"), userInfo.getString("password"), appId);
        JSONObject user = userJson.getJSONObject("userInfo");
        JSONObject result = new JSONObject();
        int expire = 60 * 24 * 10;
        if (userInfo.containsKey("expire")) {
            expire = userInfo.getIntValue("expire");
        }
        result.put("token", TokenUtil.getToken(user.toJSONString(), "123456", expire));
        result.put("userInfo", user);
        result.put("appMenus", userJson.getJSONArray("appMenus"));
        result.put("appVersion", userJson.getJSONObject("customAppVersion"));
        return result;
    }


    /**
     * 刷新token
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/refresh/token")
    public Object refresh(HttpServletRequest request) throws TokenException {
        String refresh = request.getHeader("refresh");
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(refresh)) {
            throw new TokenException("refresh is not exist");
        }
        if (StringUtils.isEmpty(token)) {
            throw new TokenException("未登录");
        }
        TokenUtil.veryRefresh(refresh, "123456");
        JSONObject result = new JSONObject();
        result.put("token", TokenUtil.getToken(TokenUtil.getBody(token), "123456", 60));
        result.put("refresh", TokenUtil.getRefreshToken("123456", 60));
        return result;
    }

    /**
     * 用户注册
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Object register(@RequestParam Map<String, Object> map, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        map.put("companyId", UserAuthUtil.getLoginUser().getCompanyId());
        return userRestService.save(map, files);
    }


    @RequestMapping(value = "/save2", method = RequestMethod.POST)
    public Object register2(@RequestBody Map<String, Object> map) throws Exception {
        map.put("companyId", UserAuthUtil.getLoginUser().getCompanyId());
        return userRestService.save2(map);
    }


    /**
     * 用户修改
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object update(@RequestParam Map<String, Object> map, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        return userRestService.update(map, files);
    }

    @RequestMapping(value = "/update2", method = RequestMethod.POST)
    public Object update2(@RequestBody Map<String, Object> map) throws Exception {
        return userRestService.update2(map);
    }

    @RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
    public Object findById(@PathVariable String id) {
        return userRestService.findById(id);
    }

    @RequestMapping(value = "/findByList", method = RequestMethod.POST)
    public Object findByList(@RequestBody JSONObject user) {
        user.put("companyId", UserAuthUtil.getLoginUser().getCompanyId());
        return userRestService.findByList(user);
    }

    @RequestMapping(value = "/findByAll", method = RequestMethod.GET)
    public Object findByAll() {
        Object byAll = userRestService.findByAll(UserAuthUtil.getLoginUser().getCompanyId());
        if (byAll != null && byAll != "") {
            JSONObject obj = JSONObject.parseObject(byAll.toString());
            Object companyObj = obj.get("CompanyObj");
            if (companyObj != null) {
                return companyObj;
            }
            return fail("companyObj为null");
        }
        return fail("查询数据为null");
    }

    @RequestMapping(value = "/checkPassword", method = RequestMethod.POST)
    public Object checkPassword(@RequestBody JSONObject param) {
        CheckParams.checkJson(param, new String[]{"userId", "password"});
        return userRestService.checkPassword(param);
    }

    /**
     * 重置密码
     */
    @PostMapping(value = "/resetpassword")
    public Object resetPassword(@RequestBody JSONObject param) {
        return userRestService.resetPassword(param);
    }

    /**
     * 重置密码
     */
    @PostMapping(value = "/changepassword")
    public Object changepassword(@RequestBody JSONObject param) {
        return userRestService.changepassword(param);
    }

    /**
     * 检验token
     */
    @GetMapping(value = "/checktoken")
    public Object checktoken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new TokenException("refresh is not exist");
        }
        return success(TokenUtil.veryToken(token, "123456"));
    }


    /**
     * 查询用户数量
     *
     * @return
     */
    @GetMapping(value = "/getUserNum")
    public Object number() {
        JSONObject jsonObject = new JSONObject();
        UserInfo userInfo = UserAuthUtil.getLoginUser();
        String userType = userInfo.getUserType();
        if (userType.equals("GOV")) {
            jsonObject.put("parentId", userInfo.getCompanyId());
        } else if ("COMMON".equals(userType) || "COMPANY".equals(userType)) {
            jsonObject.put("id", userInfo.getCompanyId());
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        return success(restTemplate.postForObject(RestURL.USERCENTER + "company/getUserNum", new HttpEntity<String>(jsonObject.toJSONString(), headers), ArrayList.class).size());
    }

    /**
     * 查询企业数量
     *
     * @return
     */
    @GetMapping(value = "/companyNumber")
    public Object companyNumber() {
        JSONObject jsonObject = new JSONObject();
        UserInfo userInfo = UserAuthUtil.getLoginUser();
        String userType = userInfo.getUserType();
        if (userType.equals("GOV")) {
            jsonObject.put("parentId", userInfo.getCompanyId());
        } else if ("COMMON".equals(userType) || "COMPANY".equals(userType)) {
            jsonObject.put("id", userInfo.getCompanyId());
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        return success(restTemplate.postForObject(RestURL.USERCENTER + "company/companyNumber", new HttpEntity<String>(jsonObject.toJSONString(), headers), ArrayList.class).size());
    }

    //获取不同平台下的公司信息
    @RequestMapping(value = "/getAppIdCompany", method = RequestMethod.GET)
    public Object getAppIdCompanyList() {
        return restService.getJsonArray(RestURL.USERCENTER + "/app/appIdlist");
    }
}
